﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Furion;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using LNSServer.Models;
using LNSServer.ViewModels.Sensor;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;

namespace LNSServer.Controllers
{
    /// <summary>
    /// 传感器
    /// </summary>
    [DynamicApiController]
    public class LnsSensorController
    {
        private readonly ILogger<LnsSensorController> logger;
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public LnsSensorController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
            this.logger = logger;
        }

        /// <summary>
        /// 传感器列表
        /// </summary>
        /// <param name="dtsf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> List([FromBody] SensorSearchForm dtsf)
        {
            RefAsync<int> total = 0;
            List<Sensor> sensors = await db.Queryable<Sensor>()
                .Where(dt => dt.IsActive == 1)
                .WhereIF(!string.IsNullOrEmpty(dtsf.Content), dt => dt.Name.Contains(dtsf.Content))
                .ToPageListAsync(dtsf.PageIndex, dtsf.PageSize, total);

            UnifyContext.Fill(new { Total = total.Value });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = sensors,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 查看传感器
        /// </summary>
        /// <param name="dtsf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Show([FromBody] SensorShowForm ssf) {
            Sensor sensor = await db.Queryable<Sensor>()
                .InSingleAsync(ssf.Id);
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = sensor,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

    }
}
